using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MVCWeb.Models;
using System.Web.Security;
using MVCWeb.Models.ViewData;
using MVCWeb.Helpers;
using System.IO;

namespace MVCWeb.Controllers
{
    public class CommunityController : BaseController
    {
        private const int defaultPageSize = 10;
        //
        // GET: /Community/
        [Authorize(Roles = "Administrators")]
        [CompressFilter]
        public ActionResult Index(int? page)
        {
            int currentPage = page.HasValue ? page.Value - 1 : 0;
            return View(dc.Communities.OrderBy(c => c.Name).ToPagedList<Community>(currentPage, defaultPageSize));
        }



        [CompressFilter]
        [Authorize]
        public ActionResult Category(int? id)
        {
            int communityId = 0;
            Community community;

            if (id.HasValue && HttpContext.User.IsInRole("Administrators"))
            {
                communityId = id.Value;
                community = dc.Communities.Where<Community>(c => c.CommunityId == id.Value).First<Community>();
            }
            else
            {
                MembershipUser membershipUser = Membership.GetUser();
                Guid membershipId = new Guid(membershipUser.ProviderUserKey.ToString());
                MVCWeb.Models.User user = dc.Users.Where<MVCWeb.Models.User>(u => u.MembershipId == membershipId).First<MVCWeb.Models.User>();
                community = dc.Communities.Where<Community>(c => c.UserId == user.UserId || c.ManagerId == user.UserId).First<Community>();
                communityId = community.CommunityId;
            }

            ViewData["CommunityName"] = community.Name;
            ViewData["CommunityId"] = community.CommunityId;
            ViewData["CurrentView"] = string.Format("Welcome to {0}", community.Name);
            if (string.IsNullOrEmpty(community.ImgUrl) == false)
            {
                ViewData["CommunityImgUrl"] = string.Format("<p><img alt='' width='530'  src='{0}' /></p>", Url.Content("~/" + community.ImgUrl));
            }
            else
            {
                ViewData["CommunityImgUrl"] = string.Empty;
            }

            IList<DocCategory> topCategories = this.dc.DocCategories.Where(c => (c.ParentDocCategoryId == 0 || c.ParentDocCategoryId.HasValue == false) && c.DocCategoryId != 1).OrderBy(c => c.Category).ToList();
            //IList<CommunityDoc> communityDoc = this.dc.CommunityDocs.ToList<CommunityDoc>();
            return View(topCategories);
        }

        [CompressFilter]
        [Authorize]
        public ActionResult AdminCategory(int? id)
        {
            int communityId = 0;
            Community community;

            if (id.HasValue && HttpContext.User.IsInRole("Administrators"))
            {
                communityId = id.Value;
                community = dc.Communities.Where<Community>(c => c.CommunityId == id.Value).First<Community>();
            }
            else
            {
                MembershipUser membershipUser = Membership.GetUser();
                Guid membershipId = new Guid(membershipUser.ProviderUserKey.ToString());
                MVCWeb.Models.User user = dc.Users.Where<MVCWeb.Models.User>(u => u.MembershipId == membershipId).First<MVCWeb.Models.User>();
                community = dc.Communities.Where<Community>(c => c.UserId == user.UserId || c.ManagerId == user.UserId).First<Community>();
                communityId = community.CommunityId;
            }

            ViewData["CommunityName"] = community.Name;
            ViewData["CommunityId"] = community.CommunityId;
            ViewData["CurrentView"] = string.Format("Welcome to {0}", community.Name);
            if (string.IsNullOrEmpty(community.ImgUrl) == false)
            {
                ViewData["CommunityImgUrl"] = string.Format("<p><img alt='' width='530' src='{0}' /></p>", Url.Content("~/" + community.ImgUrl));
            }
            else
            {
                ViewData["CommunityImgUrl"] = string.Empty;
            }

            IList<DocCategory> topCategories = this.dc.DocCategories.Where(c => (c.ParentDocCategoryId == 0 || c.ParentDocCategoryId.HasValue == false) && c.DocCategoryId != 1).OrderBy(c => c.Category).ToList();
            //IList<CommunityDoc> communityDoc = this.dc.CommunityDocs.ToList<CommunityDoc>();
            return View(topCategories);
        }



        [CompressFilter]
        [Authorize]
        public ActionResult List(int? id, int? categoryId)
        {
            try
            {
                int communityId = 0;
                Community community;

                if (id.HasValue && HttpContext.User.IsInRole("Administrators"))
                {
                    communityId = id.Value;
                    community = dc.Communities.Where<Community>(c => c.CommunityId == id.Value).First<Community>();
                }
                else
                {
                    MembershipUser membershipUser = Membership.GetUser();
                    Guid membershipId = new Guid(membershipUser.ProviderUserKey.ToString());
                    MVCWeb.Models.User user = dc.Users.Where<MVCWeb.Models.User>(u => u.MembershipId == membershipId).First<MVCWeb.Models.User>();
                    community = dc.Communities.Where<Community>(c => c.UserId == user.UserId || c.ManagerId == user.UserId).First<Community>();
                    communityId = community.CommunityId;
                }
                //Readonly don't need to track the object.
                //dc.ObjectTrackingEnabled = false;

                // if (Cache[CacheName] == null)
                // Cache[CacheName] = new SelectList(dc.Communities.ToList(), "CommunityId", "Name"); 
                // ViewData["CommunityList"] = new SelectList(dc.Communities.ToList(), "CommunityId", "Name");
                // ViewData["CommunityList"] = Cache[CacheName];

                // Get community by login user.
               

                // Get community name.
                ViewData["CommunityName"] = community.Name;
                ViewData["CommunityId"] = community.CommunityId;
                ViewData["CurrentView"] = string.Format("Welcome to {0}", community.Name);
                if (string.IsNullOrEmpty(community.ImgUrl) == false)
                {
                    ViewData["CommunityImgUrl"] = string.Format("<p><img alt='' width='530' src='{0}' /></p>", Url.Content("~/" + community.ImgUrl));
                }
                else
                {
                    ViewData["CommunityImgUrl"] = string.Empty;
                }

                IList<CommunityDoc> communityDoc = dc.CommunityDocs.Where<CommunityDoc>(x => x.CommunityId == communityId).ToList<CommunityDoc>();

                IList<Doc> listDocs = new List<Doc>();
                foreach (var item in communityDoc)
                {
                    listDocs.Add(item.Doc);
                }
                var Docs = from x in dc.Docs
                           where (from c in dc.CommunityDocs
                                  where c.CommunityId == communityId
                                  select c.DocId).Contains<int?>(x.DocId)
                           group x by x.DocCategory into r
                           select new { Category = r.Key, Docs = r };

                IList<DocCategory> docCategories = new List<DocCategory>();
                foreach (var item in Docs)
                {
                    DocCategory category = new DocCategory();
                    category.Category = item.Category.Category;
                    category.DocCategoryId = item.Category.DocCategoryId;
                    category.ParentDocCategoryId = item.Category.ParentDocCategoryId;

                    foreach (var doc in item.Docs)
                    {
                        category.Docs.Add(doc);
                    }
                    docCategories.Add(category);
                }
                return View(docCategories.Where(c => c.ParentDocCategoryId == categoryId));
            }
            catch
            {
            }
            return View(new List<DocCategory>());
        }

        //[AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        //[CompressFilter]
        //public ActionResult List(FormCollection collection)
        //{
        //    try
        //    {
        //        ViewData["CommunityList"] = new SelectList(dc.Communities.OrderBy(c => c.Name).ToList(), "CommunityId", "Name");

        //        //// Get community by login user.
        //        //MembershipUser membershipUser = Membership.GetUser();
        //        //Guid membershipId = new Guid(membershipUser.ProviderUserKey.ToString());
        //        //MVCWeb.Models.User user = dc.Users.Where<MVCWeb.Models.User>(u => u.MembershipId == membershipId).First<MVCWeb.Models.User>();
        //        //Community community = dc.Communities.Where<Community>(c => c.UserId == user.UserId || c.ManagerId == user.UserId).First<Community>();
        //        //int communityId = community.CommunityId;
        //        int communityId = Int32.Parse(collection[0]);

        //        // Get community name.
        //        //ViewData["CommunityName"] = community.Name;
        //        ViewData["CommunityId"] = communityId;
        //        //ViewData["CurrentView"] = string.Format("Welcome to {0}", community.Name);

        //        IList<CommunityDoc> communityDoc = dc.CommunityDocs.Where<CommunityDoc>(x => x.CommunityId == communityId).ToList<CommunityDoc>();

        //        IList<Doc> listDocs = new List<Doc>();
        //        foreach (var item in communityDoc)
        //        {
        //            listDocs.Add(item.Doc);
        //        }
        //        var Docs = from x in dc.Docs
        //                   where (from c in dc.CommunityDocs
        //                          where c.CommunityId == communityId
        //                          select c.DocId).Contains<int?>(x.DocId)
        //                   group x by x.DocCategory into r
        //                   select new { Category = r.Key, Docs = r };

        //        IList<DocCategory> docCategories = new List<DocCategory>();
        //        foreach (var item in Docs)
        //        {
        //            DocCategory category = new DocCategory();
        //            category.Category = Convert.ToString(item.Category.Category);
        //            category.DocCategoryId = item.Category.DocCategoryId;

        //            foreach (var doc in item.Docs)
        //            {
        //                category.Docs.Add(doc);
        //            }
        //            docCategories.Add(category);
        //        }
        //        return View(docCategories);
        //    }
        //    catch
        //    {
        //    }
        //    return View(new List<DocCategory>());
        //}

        //
        // GET: /Community/Details/5
        [Authorize]
        public ActionResult Details(int id)
        {
            return View(this.dc.Communities.SingleOrDefault<Community>(c => c.CommunityId == id));
        }

        //
        // GET: /Community/Create
        [Authorize(Roles = "Administrators")]
        public ActionResult Create()
        {
            CommunityNewViewData data = new CommunityNewViewData();
            data.Community = new Community();
            data.Companies = this.dc.Companies.OrderBy(c => c.Name).ToList<Company>();
            data.Users = this.dc.Users.Where(u => !(this.dc.Communities.Select(c => c.UserId).Contains((Int32?)(u.UserId)))).OrderBy(u => u.LogInID).ToList<User>();
            data.Managers = this.dc.Users.Where(u => !(this.dc.Communities.Select(c => c.ManagerId).Contains((Int32?)(u.UserId)))).OrderBy(u => u.LogInID).ToList<User>();
            return View(data);
        }

        //
        // POST: /Community/Create
        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult Create(Community community, FormCollection collection)
        {
            try
            {
                string newLoginId = collection["NewUserId"];
                string newManagerId = collection["NewManagerId"];
                
                User checkUser = null;
                User checkManager = null;
                if (newLoginId.Length > 0)
                {
                    checkUser = this.dc.Users.SingleOrDefault(u => u.LogInID == newLoginId);
                    if (checkUser != null)
                    {
                        ModelState.AddModelError("", "New User Login Id has been exists");
                    }
                }
                
                if (newManagerId.Length > 0)
                {
                    checkManager = this.dc.Users.SingleOrDefault(u => u.LogInID == newManagerId);
                    if (checkManager != null)
                    {
                        ModelState.AddModelError("", "New Manager Login Id has been exists");
                    }
                }

                if (ModelState.IsValid)
                {
                    if (newLoginId.Length > 0)
                    {
                        // Create new User with password.
                        string password = collection["NewUserPassword"];
                        MembershipUser mUser = Membership.CreateUser(newLoginId, password);
                        User user = new User();
                        user.LogInID = collection["NewUserId"];
                        user.MembershipId = new Guid(mUser.ProviderUserKey.ToString());
                        this.dc.Users.InsertOnSubmit(user);
                        dc.SubmitChanges();
                        community.UserId = user.UserId;
                    }
                    if (newManagerId.Length > 0)
                    {
                        if (newLoginId != newManagerId)
                        {
                            // Create new Manager with password.
                            string password = collection["NewManagerPassword"];
                            MembershipUser mManager = Membership.CreateUser(newManagerId, password);
                            User user = new User();
                            user.LogInID = collection["NewManagerId"];
                            user.MembershipId = new Guid(mManager.ProviderUserKey.ToString());
                            this.dc.Users.InsertOnSubmit(user);
                            dc.SubmitChanges();
                            community.ManagerId = user.UserId;
                        }
                        else
                        {
                            community.ManagerId = community.UserId;
                        }
                    }

                    dc.Communities.InsertOnSubmit(community);
                    dc.SubmitChanges();

                    foreach (string file in Request.Files)
                    {
                        HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                        if (hpf.ContentLength == 0)
                            continue;

                        string savePath = @"Uploads\Images\Communities\" + community.CommunityId + "\\";

                        string physicPath = AppDomain.CurrentDomain.BaseDirectory + savePath;
                        if (!Directory.Exists(physicPath))
                        {
                            Directory.CreateDirectory(physicPath);
                        }

                        string sFilename = Path.GetFileName(hpf.FileName);
                        string savedFileName = Path.Combine(physicPath, sFilename);

                        string extension = Path.GetExtension(hpf.FileName).ToLower();

                        int file_append = 0;
                        while (System.IO.File.Exists(Path.Combine(physicPath, sFilename)))
                        {
                            file_append++;
                            sFilename = System.IO.Path.GetFileNameWithoutExtension(hpf.FileName)
                                             + file_append.ToString()
                                             + extension;
                        }

                        savedFileName = Path.Combine(physicPath, sFilename);

                        hpf.SaveAs(savedFileName);

                        community.ImgUrl = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                    }

                    dc.SubmitChanges();

                    return RedirectToAction("Index");
                }
                else
                {
                    CommunityNewViewData data = new CommunityNewViewData();
                    data.Community = new Community();
                    data.Companies = this.dc.Companies.OrderBy(c => c.Name).ToList<Company>();
                    data.Users = this.dc.Users.Where(u => !(this.dc.Communities.Select(c => c.UserId).Contains((Int32?)(u.UserId)))).OrderBy(u => u.LogInID).ToList<User>();
                    data.Managers = this.dc.Users.Where(u => !(this.dc.Communities.Select(c => c.ManagerId).Contains((Int32?)(u.UserId)))).OrderBy(u => u.LogInID).ToList<User>();
                    return View(data);
                }
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Community/Edit/5
        [Authorize(Roles = "Administrators")]
        public ActionResult Edit(int id)
        {
            CommunityNewViewData data = new CommunityNewViewData();
            data.Community = dc.Communities.Single<Community>(c => c.CommunityId == id);
            data.Companies = this.dc.Companies.OrderBy(c => c.Name).ToList<Company>();
            data.Users = this.dc.Users.Where(u => !(this.dc.Communities.Select(c => c.UserId).Contains((Int32?)(u.UserId)))).Union(this.dc.Users.Where(u=>u.UserId==data.Community.UserId)).OrderBy(u => u.LogInID).ToList<User>();
            data.Managers = this.dc.Users.Where(u => !(this.dc.Communities.Select(c => c.ManagerId).Contains((Int32?)(u.UserId)))).Union(this.dc.Users.Where(u => u.UserId == data.Community.ManagerId)).OrderBy(u => u.LogInID).ToList<User>();
            
            /*
            Community community = dc.Communities.First<Community>(x => x.CommunityId == id);

            var users = dc.Users.ToList<User>();
            ViewData["UserId"] = new SelectList(users, "UserId", "LogInID",community.UserId);

            var companies = dc.Companies.ToList<Company>();
            ViewData["CompanyId"] = new SelectList(companies, "CompanyId", "Name", community.CompanyId);

            var managers = dc.Users.ToList<User>();
            ViewData["ManagerId"] = new SelectList(managers, "UserId", "LogInID", community.ManagerId);
            */
            return View(data);
            
        }

        //
        // POST: /Community/Edit/5

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult Edit(int id, Community community, FormCollection collection)
        {
            try
            {
                community = this.dc.Communities.Single(c => c.CommunityId == id);
                string newLoginId = collection["NewUserId"];
                string newManagerId = collection["NewManagerId"];

                string newLoginPassword = collection["NewUserPassword"];
                string newManagerPassword = collection["NewManagerPassword"];

                User checkUser = null;
                User checkManager = null;
                if (newLoginId.Length > 0)
                {
                    checkUser = this.dc.Users.SingleOrDefault(u => u.LogInID == newLoginId);
                    if (checkUser != null)
                    {
                        ModelState.AddModelError("", "New User Login Id has been exists");
                    }
                }

                if (newManagerId.Length > 0)
                {
                    checkManager = this.dc.Users.SingleOrDefault(u => u.LogInID == newManagerId);
                    if (checkManager != null)
                    {
                        ModelState.AddModelError("", "New Manager Login Id has been exists");
                    }
                }

                if (ModelState.IsValid)
                {
                    if (newLoginId.Length > 0)
                    {
                        // Create new User with password.
                        string password = collection["NewUserPassword"];
                        MembershipUser mUser = Membership.CreateUser(newLoginId, password);
                        User user = new User();
                        user.LogInID = collection["NewUserId"];
                        user.MembershipId = new Guid(mUser.ProviderUserKey.ToString());
                        this.dc.Users.InsertOnSubmit(user);
                        dc.SubmitChanges();
                        community.UserId = user.UserId;
                    }
                    else if (newLoginPassword.Length > 0)
                    {
                        // Change password.
                        User user = this.dc.Users.Single<User>(u => u.UserId == community.UserId);
                        MembershipUser mu = Membership.GetUser(user.LogInID);
                        mu.ChangePassword(mu.ResetPassword(), newLoginPassword);
                    }

                    if (newManagerId.Length > 0)
                    {
                        if (newLoginId != newManagerId)
                        {
                            // Create new Manager with password.
                            string password = collection["NewManagerPassword"];
                            MembershipUser mManager = Membership.CreateUser(newManagerId, password);
                            User user = new User();
                            user.LogInID = collection["NewManagerId"];
                            user.MembershipId = new Guid(mManager.ProviderUserKey.ToString());
                            this.dc.Users.InsertOnSubmit(user);
                            dc.SubmitChanges();
                            community.ManagerId = user.UserId;
                        }
                        else
                        {
                            community.ManagerId = community.UserId;
                        }
                    }
                    else if (newManagerPassword.Length > 0)
                    {
                        // Change password.
                        User user = this.dc.Users.Single<User>(u => u.UserId == community.ManagerId);
                        MembershipUser mu = Membership.GetUser(user.LogInID);
                        mu.ChangePassword(mu.ResetPassword(), newManagerPassword);
                    }

                    foreach (string file in Request.Files)
                    {
                        FileInfo oldFile = new FileInfo(Server.MapPath("~/" + community.ImgUrl));
                        if (oldFile.Exists)
                        {
                            oldFile.Delete();
                        }

                        HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                        if (hpf.ContentLength == 0)
                            continue;

                        string savePath = @"Uploads\Images\Communities\" + community.CommunityId + "\\";

                        string physicPath = AppDomain.CurrentDomain.BaseDirectory + savePath;
                        if (!Directory.Exists(physicPath))
                        {
                            Directory.CreateDirectory(physicPath);
                        }

                        string sFilename = Path.GetFileName(hpf.FileName);
                        string savedFileName = Path.Combine(physicPath, sFilename);

                        string extension = Path.GetExtension(hpf.FileName).ToLower();

                        int file_append = 0;
                        while (System.IO.File.Exists(Path.Combine(physicPath, sFilename)))
                        {
                            file_append++;
                            sFilename = System.IO.Path.GetFileNameWithoutExtension(hpf.FileName)
                                             + file_append.ToString()
                                             + extension;
                        }

                        savedFileName = Path.Combine(physicPath, sFilename);

                        hpf.SaveAs(savedFileName);

                        community.ImgUrl = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                    }

                    UpdateModel<Community>(community);
                    dc.SubmitChanges();
                    return RedirectToAction("Index");
                }
                else
                {
                    CommunityNewViewData data = new CommunityNewViewData();
                    data.Companies = this.dc.Companies.OrderBy(c => c.Name).ToList<Company>();
                    data.Users = this.dc.Users.Where(u => !(this.dc.Communities.Select(c => c.UserId).Contains((Int32?)(u.UserId)))).OrderBy(u => u.LogInID).ToList<User>();
                    data.Managers = this.dc.Users.Where(u => !(this.dc.Communities.Select(c => c.ManagerId).Contains((Int32?)(u.UserId)))).OrderBy(u => u.LogInID).ToList<User>();
                    data.Community = dc.Communities.Single<Community>(c => c.CommunityId == id);
                    return View(data);
                }
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Community/Details/5
        [Authorize]
        public ActionResult CommunityVendor(int id)
        {
            try
            {
                ViewData["CommunityId"] = id;
                Community community = this.dc.Communities.Single(c => c.CommunityId == id);
                if (string.IsNullOrEmpty(community.ImgUrl) == false)
                {
                    ViewData["CommunityImgUrl"] = string.Format("<p><img alt='' width='530' src='{0}' /></p>", Url.Content("~/" + community.ImgUrl));
                }
                else
                {
                    ViewData["CommunityImgUrl"] = string.Empty;
                }
            }
            catch { }

            return View();
        }

        //
        // GET: /Community/Details/5
        [Authorize]
        public ActionResult Ref(int id)
        {
            try
            {
                ViewData["CommunityId"] = id;
                Community community = this.dc.Communities.Single(c => c.CommunityId == id);
                if (string.IsNullOrEmpty(community.ImgUrl) == false)
                {
                    ViewData["CommunityImgUrl"] = string.Format("<p><img alt='' width='530' src='{0}' /></p>", Url.Content("~/" + community.ImgUrl));
                }
                else
                {
                    ViewData["CommunityImgUrl"] = string.Empty;
                }
            }
            catch { }

            return View();
        }

        //
        // GET: /Community/Details/5
        [Authorize]
        public ActionResult Event(int id)
        {
            try
            {
                ViewData["CommunityId"] = id;
                Community community = this.dc.Communities.Single(c => c.CommunityId == id);
                if (string.IsNullOrEmpty(community.ImgUrl) == false)
                {
                    ViewData["CommunityImgUrl"] = string.Format("<p><img alt='' width='530' src='{0}' /></p>", Url.Content("~/" + community.ImgUrl));
                }
                else
                {
                    ViewData["CommunityImgUrl"] = string.Empty;
                }
            }
            catch { }

            return View();
        }

        //
        // GET: /Community/Details/5
        [Authorize]
        public ActionResult Staff(int id)
        {
            try
            {
                ViewData["CommunityId"] = id;
                Community community = this.dc.Communities.Single(c => c.CommunityId == id);
                if (string.IsNullOrEmpty(community.ImgUrl) == false)
                {
                    ViewData["CommunityImgUrl"] = string.Format("<p><img alt='' width='530' src='{0}' /></p>", Url.Content("~/" + community.ImgUrl));
                }
                else
                {
                    ViewData["CommunityImgUrl"] = string.Empty;
                }
            }
            catch { }

            return View();
        }

        //
        // GET: /Community/Details/5
        [Authorize]
        public ActionResult Home(int id)
        {
            try
            {
                ViewData["CommunityId"] = id;
                Community community = this.dc.Communities.Single(c => c.CommunityId == id);
                if (string.IsNullOrEmpty(community.ImgUrl) == false)
                {
                    ViewData["CommunityImgUrl"] = string.Format("<p><img alt='' width='530' src='{0}' /></p>", Url.Content("~/" + community.ImgUrl));
                }
                else
                {
                    ViewData["CommunityImgUrl"] = string.Empty;
                }
            }
            catch { }

            return View();
        }

        //
        // GET: /Community/Details/5
        [Authorize]
        public ActionResult UtilityRef(int id)
        {
            try
            {
                ViewData["CommunityId"] = id;
                Community community = this.dc.Communities.Single(c => c.CommunityId == id);
                if (string.IsNullOrEmpty(community.ImgUrl) == false)
                {
                    ViewData["CommunityImgUrl"] = string.Format("<p><img alt='' width='530' src='{0}' /></p>", Url.Content("~/" + community.ImgUrl));
                }
                else
                {
                    ViewData["CommunityImgUrl"] = string.Empty;
                }
            }
            catch { }

            return View();
        }

        //
        // GET: /Community/Details/5
        [Authorize]
        //public ActionResult ResourceInfo(int id)
        public ActionResult ResourceInfo(int id)
        {
            try
            {
                ViewData["CommunityId"] = id;
                Community community = this.dc.Communities.Single(c => c.CommunityId == id);
                if (string.IsNullOrEmpty(community.ImgUrl) == false)
                {
                    ViewData["CommunityImgUrl"] = string.Format("<p><img alt='' width='530' src='{0}' /></p>", Url.Content("~/" + community.ImgUrl));
                }
                else
                {
                    ViewData["CommunityImgUrl"] = string.Empty;
                }
            }
            catch { }

            return View();
        }

        [Authorize(Roles = "Administrators")]
        public ActionResult AdminList(int? page)
        {
            int currentPage = page.HasValue ? page.Value - 1 : 0;
            return View(dc.Communities.OrderBy(c => c.Name).ToPagedList<Community>(currentPage, defaultPageSize));
        }

    }
}
